package com.jack.leetcode.eachProblem08;

public class 图像渲染 {

    int[][] dir = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        int[][] dp = new int[image.length][image[0].length];
        dfs(dp, image, sr, sc, image[sr][sc], newColor);
        return image;
    }

    private void dfs(int[][] dp, int[][] image, int sr, int sc, int original, int newColor) {
        if (isValid(image, sr, sc) && image[sr][sc] == original && dp[sr][sc] == 0) {
            image[sr][sc] = newColor;
            dp[sr][sc] = 1;
            for (int[] d : dir) {
                dfs(dp, image, sr + d[0], sc + d[1], original, newColor);
            }
        }
    }

    private boolean isValid(int[][] image, int sr, int sc) {
        return sr >= 0 && sr < image.length && sc >= 0 && sc < image[0].length;
    }
}
